import React, { Component } from 'react'
// import './index.scss'
import logo from 'assets/logo.png'
import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import { loginApi } from 'api/user'
import styles from './index.module.scss' // 测试CSS Modules
import { setToken } from 'utils/storage'

export default class Login extends Component {
  // 登录
  onFinish = async (value) => {
    const { state } = this.props.location
    try {
      const res = await loginApi(value)
      // console.log('登录', res)
      // 得到的是两个对象，所以需要通过JSON来转换
      // localStorage.setItem('geek-token', JSON.stringify(res.data))
      setToken(JSON.stringify(res))
      if (state) {
        this.props.history.push(state.from)
      } else {
        this.props.history.push('/home')
      }
      message.success('登陆成功')
    } catch (error) {
      message.error('登录失败')
      console.log(error)
    }
  }
  render() {
    return (
      <div className={styles.login}>
        {/* <div className={styles.box}>123</div> */}
        <Card className="login-container">
          <img src={logo} className="login-logo" alt="" />
          <Form
            name="basic"
            size="large"
            validateTrigger={['onChange', 'onBlur']}
            onFinish={this.onFinish}
            initialValues={{
              agree: true,
              mobile: '13888888888',
              code: '246810',
            }}
          >
            <Form.Item
              name="mobile"
              rules={[
                { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不对' },
                { required: true, message: '请输入手机号' },
              ]}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>

            <Form.Item
              name="code"
              rules={[
                { pattern: /^\d{6}$/, message: '验证码格式不对' },
                { required: true, message: '请输入验证码' },
              ]}
            >
              <Input placeholder="请输入验证码" />
            </Form.Item>

            <Form.Item
              name="agree"
              valuePropName="checked"
              rules={[
                {
                  validator(_, value) {
                    // console.log(value)   // true
                    return value
                      ? Promise.resolve()
                      : Promise.reject(new Error('请勾选协议'))
                  },
                },
              ]}
            >
              <Checkbox>我已阅读并同意[用户协议]和[隐私条款]</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit" block>
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
}
